<?php
/*****************************************************************
 * Fusion.Board
 *
 * @author                Denis Wrobel
 * @license               http://www.gnu.org/licenses/gpl-3.0.html
 * @version               0.1
 *
 *****************************************************************/

if( !defined( 'IN_SCRIPT' ) )
{
    die( 'Go Away!' );
}

$page->title = $language->string( 'register' );
$page->addBreadcrumb( 'index.php?action=register', $language->string( 'register' ) );

if( $session['session_logged'] )
{
    $page->error( $language->string( 'you_are_already_logged_in' ) );
}

if( !$core->_GET( 'step' ) )
{
    $template->assignVars( array( 'rules'     => $language->string( 'rules' ),
                                  'l_accept'  => $language->string( 'i_accept_rules' ),
                                  'l_decline' => $language->string( 'i_dont_accept_rules' ) ) );
    
    
    $page->drawHeader();
    $template->draw( 'register_rules' );
    $page->drawFooter();
}
else
{
    if( $core->_POST( 'decline' ) )
    {
        $page->error( $language->string( 'sorry_rules_must_be_accepted' ) );
    }
    else
    {
        $extraFields = $core->getExtraFields( 'on_register' );
        $extraFieldsSql = '';
        
        if( $core->_POST( 'submit' ) )
        {
            $errors = 0;
            $error_message = '';
            
            $username = $core->filterItem( $core->_POST( 'username', 1 ) );
            $password = $core->_POST( 'password' );
            $repassword = $core->_POST( 'repassword' );
            $email = $core->filterItem( $core->_POST( 'email' ) );
            
            if( strlen( $username ) < 3 )
            {
                $errors++;
                $error_message .= $language->string( 'username_too_short' ) . '<br />';
            }
            elseif( strlen( $username ) > $board['max_username_len'] )
            {
                $errors++;
                $error_message .= $language->string( 'username_too_long' ) . '<br />';
            }
            elseif( !$core->isUsername( $username ) )
            {
                $errors++;
                $error_message .= $language->string( 'invalid_username' ) . '<br />';
            }
            
            if( isset( $username ) && $core->isUsernameInUse( $db->escape( $username ) ) )
            {
                $errors++;
                $error_message .= $language->string( 'username_is_in_use' ) . '<br />';
            }
            
            if( strlen( $password ) < 4 )
            {
                $errors++;
                $error_message .= $language->string( 'password_too_short' ) . '<br />';
            }
            elseif( $password != $repassword )
            {
                $errors++;
                $error_message .= $language->string( 'passwords_are_not_the_same' ) . '<br />';
            }
            
            if( !$core->isEmail( $email ) )
            {
                $errors++;
                $error_message .= $language->string( 'invalid_email' ) . '<br />';
            }
            elseif( isset( $email ) && $core->isEmailInUse( $db->escape( $email ) ) )
            {
                $errors++;
                $error_message .= $language->string( 'email_in_use' ) . '<br />';
            }
            
            if( count( $extraFields ) )
            {
                foreach( $extraFields AS $extraField )
                {
                    $formValue = $core->filterItem( $core->_POST( 'field_' . $extraField['field_id'] ) );
                    
                    
                    if(  $extraField['field_maxlength'] && strlen( $formValue ) > $extraField['field_maxlength'] )
                    {
                        $errors++;
                        $error_message .= $language->sprintf( '{1} "<b>{2}</b>" {3}', $language->string( 'field_value' ),
                                                                                    $core->htmlFilter( $extraField['field_name'] ),
                                                                                    $language->string( 'field_value_too_long', 0 ) ) . '<br />';
                    }
                    elseif( !strlen( $formValue ) && $extraField['is_required'] )
                    {
                        $errors++;
                        $error_message .= $language->sprintf( '{1} "<b>{2}</b>" {3}', $language->string( 'field' ),
                                                                                      $core->htmlFilter( $extraField['field_name'] ),
                                                                                      $language->string( 'field_is_required', 0 ) ) . '<br />';
                    }
                    elseif( strlen( $formValue ) )
                    {
                        if( !$extraFieldsSql )
                        {
                            $extraFieldsSql .= 'INSERT INTO ' . TABLE_PREFIX . 'extra_fields_data VALUES ';
                        }
                        
                        $extraFieldsSql .= '( ' . $extraField['field_id'] . ', (SELECT ( MAX(user_id) + 1 ) FROM ' . TABLE_PREFIX . 'users ), \'' . $db->escape( $core->_POST( 'field_' . $extraField['field_id'] ) ) . '\'), ';
                    }
                }
            }
            
            $extraFieldsSql = substr( $extraFieldsSql, 0, strlen( $extraFieldsSql ) - 2 );
            
            //$captchaResponse = $recaptcha->recaptcha_check_answer( $_SERVER['REMOTE_ADDR'],
            //                                                       $core->_POST( 'recaptcha_challenge_field' ),
            //                                                       $core->_POST( 'recaptcha_response_field' ) );

            //if (!$captchaResponse->is_valid)
            //{
            //    $errors++;
            //    $error_message .= $language->string( 'invalid_code' ) . '<br />';
            //}
            
            if( $errors )
            {
                $template->assignVars( array( 'l_error_occured' => $language->string( 'error_occured' ),
                                              'error_message'   => $error_message,
                                              'username'        => $core->htmlFilter( $username ),
                                              'email'           => $core->htmlFilter( $email ) ) );
                
                $template->setIf( 'errors' );
            }
            else
            {
                $activate_key = substr( md5( microtime() ), 0, 32 );
                
                $insertUser = $user->addUser( $db->escape( $username ), $password, $db->escape( $email ), $activate_key ); //Add user
                
                if( $insertUser )
                {
                    //Registration OK
                    
                    $db->query( $extraFieldsSql ); //Insert extra fields data
                    
                    if( $board['account_activation'] )
                    {
                        $sendMail = $mail->send_mail( $email, $language->string( 'account_activation' ) . ' - ' . $board['board_title'] ,
                                                      $language->sprintf( $language->string( 'account_activation_mail' ),
                                                                          $core->htmlFilter( $username ) . '<br />',
                                                                          '<a href="' . $board['board_url'] . '">' . $board['board_title'] . '</a>',
                                                                          '<a href="' . $board['board_url'] . 'index.php?action=acc_activate&u=' . $insertUser . '&key=' . $activate_key . '">' . $board['board_url'] . 'index.php?action=acc_activate&u=' . $insertUser . '&key=' . $activate_key . '</a>') );
                    
                        if( $sendMail )
                        {
                            $page->redirect( 'index.php', $language->string( 'register_succes_mail_sended' ) );
                        }
                        else
                        {
                            $error->scriptError( 'Something gone wrong while sending email' );
                        }
                    }
                    else
                    {
                        $page->redirect( 'index.php', $language->string( 'register_succes' ) );
                    }
                }
                else
                {
                    //registration false
                    $error->scriptError( 'Something gone wrong while adding new user' );
                }
            }
        }
        
        if( count( $extraFields ) )
        {
            foreach( $extraFields AS $extraField )
            {
                $template->setLoop( 'extraFields', array( 'field_name'  => $core->htmlFilter( $extraField['field_name'] ) . ( ( $extraField['is_required'] ) ? '*' : '' ),
                                                          'field_descp' => $core->htmlFilter( $extraField['field_description'] ),
                                                          'field_id'    => $extraField['field_id'],
                                                          'maxlength'   => ( $extraField['field_maxlength'] ) ? $extraField['field_maxlength'] : '',
                                                          'value'       => $core->htmlFilter( $core->_POST( 'field_' . $extraField['field_id'] ) ) ) );
            }
        }
        
        $template->assignVars( array( 'l_register'       => $language->string( 'register' ),
                                      'l_main_acc_info'  => $language->string( 'main_account_info' ),
                                      'l_username'       => $language->string( 'username' ),
                                      'l_password'       => $language->string( 'password' ),
                                      'l_repassword'     => $language->string( 'repeat_password' ),
                                      'l_email'          => $language->string( 'email' ),
                                      'recaptcha'        => '',
                                      'l_recaptcha_info' => $language->string( 'recaptcha_info' ),
                                      'l_extra_fields'   => $language->string( 'extra_fields' ) ) );
        
        $page->drawHeader();
        $template->draw( 'register' );
        $page->drawFooter();
    }
}